﻿using System;
using System.Windows;
using Microsoft.Win32;

namespace Outcoder.Calcium.VSIntegration
{
	class RegistryUtil
	{
		public static string GetCalciumInstallDirectory(CalciumProduct version, string vsVersion, string calciumVersion)
		{
			bool is64Bit = Environment.Is64BitOperatingSystem;
			string registreyKey;
			string keyStart = @"SOFTWARE\" + (is64Bit ? @"Wow6432Node\" : string.Empty);

			if (version == CalciumProduct.Phone)
			{
				if (calciumVersion == "1.0")
				{
					registreyKey = keyStart + @"Outcoder\Calcium\Windows Phone\8.0\Setup";
				}
				else
				{
					registreyKey = keyStart + @"Outcoder\Calcium\Windows Phone\" + calciumVersion + @"\Setup";
				}
			}
			else if (version == CalciumProduct.WinRT)
			{
				registreyKey = keyStart + @"Outcoder\Calcium\Windows Store\VS" + vsVersion + @"\Setup";
			}
			else
			{
				registreyKey = keyStart + @"Daniel Vaughan\Calcium SDK VS" + vsVersion + @"\" + calciumVersion + @"\Setup";
			}

			if (Environment.MachineName.ToLower() == "energia")
			{
				MessageBox.Show(registreyKey);
			}

			RegistryKey regKey = null;
			try
			{
				regKey = Registry.LocalMachine.OpenSubKey(registreyKey);

				if (regKey == null)
				{
					throw new Exception("Unable to locate registry entry at: " + registreyKey);
				}

				var installDir = regKey.GetValue("InstallDir");
				if (installDir == null)
				{
					throw new Exception("Unable to locate registry entry value for InstallDir at: " + registreyKey);
				}

				string result = installDir.ToString();

				if (string.IsNullOrWhiteSpace(result))
				{
					throw new Exception("Path is empty in the registry entry value for InstallDir at: " + registreyKey);
				}

				return installDir.ToString();
			}
			finally
			{
				if (regKey != null)
				{
					regKey.Close();
				}
			}
		}
	}
}
